#include "WorldConnection.h"
#include "SessionManager.h"


WorldConnection::WorldConnection(boost::asio::io_service& io_service, 
								 ConnectionClosedListener* listerner) :
	RpcConnection(io_service,listerner)
{
}

WorldConnection::~WorldConnection(void)
{
}

void WorldConnection::login(::google::protobuf::RpcController* controller,
				   const ::RPC::LoginRequest* request,
				   ::RPC::CommonResponse* response,
				   ::google::protobuf::Closure* done)
{
	if (m_session.get() == NULL)
	{
		LOG_INFO << "login: " << request->name() << " ," << request->password();
		response->set_resault(0);
		response->set_message("");
		done->Run();

		m_session.reset(new SessionSerivce(1,"lindm"));
 		sSessionManager.queueHandler(SimpleHandle(
 			boost::bind(&SessionManager::addSession,&sSessionManager,m_session))
 			);
	}
}

void WorldConnection::onHandleRequest(RequestHead& rh, ArrayBuffer& buffer)
{
	if (m_session.get() == NULL)
	{
		CallServiceMethod(this,rh.method,buffer);
	}
	else
	{
		const ::google::protobuf::MethodDescriptor* md = 
			m_session->GetDescriptor()->method(rh.method);

		if (md)
		{
			::google::protobuf::Message* req = m_session->GetRequestPrototype(md).New();

			if (!req->ParseFromArray(buffer.data(),buffer.size()))
			{
				delete req;
				return;
			}

			::google::protobuf::Message* res = m_session->GetResponsePrototype(md).New();
			RpcController* ctl = new RpcController;

			RPCClosure* closure = RPCClosure::New(
				boost::bind(&RpcConnection::onCallServiceMethodCallback,shared_from_this(),md,ctl,req,res));

			CallMethodData dat(md,ctl,req,res,closure);
			m_session->queueHandler(CallMethodHandle(m_session.get(),dat));
		}
		
	}
}

void WorldConnection::onHandleResponse(ResponseHead& rh, ArrayBuffer& buffer)
{

}